package com.heima.comment.limiter;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;

public class RequestLimiter {

    private final StringRedisTemplate redisTemplate;

    public RequestLimiter(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean allowRequest(String key) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        // 尝试获取当前计数
        String count = ops.get(key);
        if (count != null && Integer.parseInt(count) >= 1) {
            // 如果计数已达到1，则拒绝请求
            return false;
        }
        // 增加计数
        ops.increment(key, 1);
        // 设置键的过期时间为5秒
        redisTemplate.expire(key, 5, TimeUnit.SECONDS);
        return true;
    }
}